package Song.Han.Demo02;

import java.io.*;
import java.net.Socket;

/*
    文件上传案例的客户端实现

    数据源：E:\IDeaProject\Day14\src\Song\Han\Demo01\证件照.png
*/
public class TCPClient {
    public static void main(String[] args) throws IOException {
        //1.创建本地输入流
        //1.1 创建输入流，读取本地文件
        BufferedInputStream bisLocal = new BufferedInputStream(new FileInputStream("E:\\IDeaProject\\Day14\\src\\Song\\Han\\Demo01\\证件照.png"));
        //1.2 创建输出流，写到服务端
        Socket socket = new Socket("localhost",6666);
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        //2. 写出数据
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = bisLocal.read(bytes)) != -1){
            bos.write(bytes,0,len);
            bos.flush();
        }

        //服务器端接收不到-1，故陷入死循环
        socket.shutdownOutput();//***正常结束输出流
        System.out.println("文件发送完毕");

        //3. 读取服务器回写的内容
        InputStream is = socket.getInputStream();
        while ((len = is.read(bytes)) != -1){
            System.out.println(new String(bytes,0,len));
        }


        //4. 释放资源
        bos.close();
        socket.close();

        bisLocal.close();
        is.close();
    }
}
